import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import '../models/community_info.dart';

class CommunityExportService {
  /// 导出小区数据到JSON文件
  static Future<String?> exportToJson(List<CommunityInfo> communities) async {
    try {
      // 请求存储权限
      var status = await Permission.storage.request();
      if (!status.isGranted) {
        return null;
      }

      // 获取下载目录
      Directory? directory;
      if (Platform.isAndroid) {
        directory = Directory('/storage/emulated/0/Download');
      } else {
        directory = await getDownloadsDirectory();
      }

      if (directory == null) {
        return null;
      }

      // 创建导出文件名
      final timestamp = DateTime.now().millisecondsSinceEpoch;
      final fileName = 'community_data_$timestamp.json';
      final file = File('${directory.path}/$fileName');

      // 转换数据为JSON
      final jsonData = communities.map((c) => c.toJson()).toList();
      final jsonString = jsonEncode(jsonData);

      // 写入文件
      await file.writeAsString(jsonString);
      return file.path;
    } catch (e) {
      print('导出数据失败: $e');
      return null;
    }
  }

  /// 从JSON文件导入小区数据
  static Future<List<CommunityInfo>?> importFromJson(String filePath) async {
    try {
      final file = File(filePath);
      if (!await file.exists()) {
        return null;
      }

      final jsonString = await file.readAsString();
      final List<dynamic> jsonList = jsonDecode(jsonString);
      return jsonList.map((json) => CommunityInfo.fromJson(json)).toList();
    } catch (e) {
      print('导入数据失败: $e');
      return null;
    }
  }
} 